package demo2;

import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;

//定时器模拟实现


//通过MytimerTask这个类描述了一个任务。
class MyTimerTask{
private Runnable runnable;//一个要执行的任务,一会肯定要写这个任务代码
    private long time;//执行时间
    public MyTimerTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }


    //下面重写一下compare
    public int compareTo(MyTimerTask o){
        return (int)(this.time - o.time);
    }
    public long getTime(){
        return time;
    }
    public Runnable getRunnable(){
        return runnable;
    }
}


//定时器
class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();//优先级队列存储任务
    private Object loker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (loker) {
            queue.offer(new MyTimerTask(runnable, delay));
            loker.notify();
        }
    }

    //创建扫描线程，扫描队首元素看是否到达时间
    public MyTimer() {
        Thread t = new Thread(() -> {
            try {
                synchronized (loker) {
                    while (true) {
                        while (queue.isEmpty()) {
                            loker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {//到时间了
                            task.getRunnable().run();//执行
                            queue.poll();
                        } else {
                            loker.wait(task.getTime() - curTime);
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }
}
public class test {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable(){
@Override
public void run(){
    System.out.println("111");
}
        } ,3000);
        System.out.println("开始");
    }
}

